package com.meida.app.provider.controller;

import cn.hutool.core.util.RandomUtil;
import com.meida.common.constants.CommonConstants;
import com.meida.common.constants.SettingConstant;
import com.meida.common.enums.SmsCodeTypeEnum;
import com.meida.common.handler.SmsSendHandler;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.utils.*;
import com.meida.module.user.client.entity.AppAccount;
import com.meida.module.user.provider.service.AppAccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

import static com.meida.common.constants.CommonConstants.*;
import static com.meida.common.enums.SmsCodeTypeEnum.REG;
import static com.meida.common.enums.SmsCodeTypeEnum.UPDATE;

/**
 * @author: zyf
 * @date: 2018/11/9 15:43
 * @description: 通用模块接口, 不需要登录鉴权的接口
 */
@Api(tags = "公共服务")
@RestController
@RequestMapping("/common")
public class AppCommonController {

    @Autowired
    private RedisUtils redisUtils;


    @Autowired
    private AppAccountService appAccountService;

    /**
     * 获取验证码
     *
     * @param useType 1:注册、换绑手机号,2:找回密码,3绑定手机号
     * @param mobile
     * @return
     */
    @ApiOperation(value = "获取验证码", notes = "useType说明:REG用于注册、绑定新手机号,UPDATE用户忘记密码,修改密码")
    @PostMapping("/getSmsCode")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", required = true, value = "手机号", paramType = "form", defaultValue = "tf4E9/6ZWDVBmn+LHhAMDg=="),
            @ApiImplicitParam(name = "areaCode", value = "区号", paramType = "form"),
            @ApiImplicitParam(name = "accountType", value = "账户类型", paramType = "form"),
            @ApiImplicitParam(name = "encryption", value = "是否加密", paramType = "form"),
            @ApiImplicitParam(name = "useType", required = true, value = "验证码用途", paramType = "form")
    })
    public ResultBody getSmsCode(SmsCodeTypeEnum useType, String mobile, Integer encryption, @RequestParam(value = "areaCode", defaultValue = "+86", required = false) String areaCode, @RequestParam(value = "accountType", required = false) String accountType) {
        EntityMap map = redisUtils.getConfigMap("SMS_CONFIG");
        Boolean encryptionTag = map.get(SettingConstant.SMS_ENCRYPTION, false);
        String tel = mobile;
        if (FlymeUtils.isNotEmpty(encryptionTag) && encryptionTag) {
            //解密手机号
            tel = Des3Util.decode(mobile);
        }
        if (FlymeUtils.isNotEmpty(encryption)) {
            tel = mobile;
        }
        ApiAssert.isTrue("手机号非法", StringUtils.isPhoneLegal(tel, areaCode));
        ApiAssert.isNotEmpty("验证码用途不能为空", useType);
        if (!CommonConstants.SMS_USETYPE_BIND.equals(useType.getCode())) {
            //手机号是否已注册
            Boolean tag = appAccountService.checkByAccountName(tel);
            if (SMS_USETYPE_REG.equals(useType.getCode()) || REG.equals(useType)) {
                if (tag) {
                    return ResultBody.failed("手机号已注册");
                }
            }
            if (SMS_USETYPE_UPDATE.equals(useType.getCode()) || UPDATE.equals(useType)) {
                if (!tag) {
                    return ResultBody.failed("账号不存在");
                }
            }
            if (SMS_USETYPE_LOGIN.equals(useType.getCode())) {

            }
        } else {
            AppAccount account = appAccountService.getMobileAccount(tel);
            if (FlymeUtils.isNotEmpty(account)) {
                Long userId = account.getUserId();

                if (FlymeUtils.isNotEmpty(userId)) {
                    Boolean check = appAccountService.isExist(userId, accountType);
                    if (check) {
                        return ResultBody.failed("该账号已绑定");
                    }
                }
            }
        }
        Integer code = RandomUtil.randomInt(100000, 999999);
        //保存验证码
        redisUtils.set(CommonConstants.PRE_SMS + tel, code, 900);
        Boolean enable = map.get(SettingConstant.OPEN_SMS, false);
        Map<String, Integer> params = new HashMap<>(3);
        params.put("code", code);
        if (enable) {
            String handlerName = map.get(SettingConstant.SMSCODE_HANDLER, "");
            //发送验证码
            SmsSendHandler smsSendHandler = SpringContextHolder.getHandler(handlerName, SmsSendHandler.class);
            if (FlymeUtils.isNotEmpty(smsSendHandler)) {
                smsSendHandler.send(tel, code, areaCode);
                return ResultBody.msg("发送成功").data(params);
            } else {
                return ResultBody.failed("请设置短信发送处理器");
            }
        } else {
            return ResultBody.ok("发送成功", params);
        }
    }


    /**
     * 获取加密手机号
     *
     * @param mobile
     * @return
     */
    @ApiOperation(value = "加密手机号", notes = "获取加密手机号")
    @PostMapping("/getMobile")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", required = true, value = "手机号", paramType = "form")
    })
    public ResultBody getMobile(String mobile) {
        String key1 = Des3Util.encode(mobile);
        return ResultBody.ok("获取成功", key1);
    }

    /**
     * 修改密码
     */
    @ApiOperation(value = "修改密码(验证码)", notes = "根据验证码修改密码")
    @PostMapping("resetPwdBySmsCode")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "smsCode", required = true, value = "验证码", paramType = "form"),
            @ApiImplicitParam(name = "mobile", required = true, value = "手机号", paramType = "form", defaultValue = "18739941307"),
            @ApiImplicitParam(name = "newPassword", required = true, value = "新密码", paramType = "form")
    })
    public ResultBody resetPwdBySmsCode(@RequestParam(value = "mobile") String mobile,
                                        @RequestParam(value = "smsCode") String smsCode,
                                        @RequestParam(value = "newPassword") String newPassword
    ) {
        appAccountService.resetPwdBySmsCode(mobile, smsCode, newPassword);
        return ResultBody.msg("修改成功");
    }

}
